package cn.dazhou.railway.bindremoteservice

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log

/**
 * 目前发现在一些Android11手机上，当远程服务App有Activity时，是可以绑定远程服务的。而在一台Android10的电话机上却不行。
 */
class RemoteService : Service() {

    companion object {
        private const val CHANNEL_ID = "ForegroundServiceChannel"
        private const val NOTIFICATION_ID = 1
    }

    private val dzEngine = DzEngine()

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForegroundService()
        Log.i("ABCD", "onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i("ABCD", "onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder {
        Log.i("ABCD", "onBind")
        return dzEngine
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.i("ABCD", "onUnbind")
        return super.onUnbind(intent)
    }

    @SuppressLint("ObsoleteSdkInt")
    override fun onDestroy() {
        Log.i("ABCD", "onDestroy")
        // 移除前台状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            stopForeground(STOP_FOREGROUND_REMOVE)
        } else {
            @Suppress("DEPRECATION")
            stopForeground(true)
        }
        super.onDestroy()
    }

    class DzEngine : IDzEngine.Stub() {
        override fun hello(name: String): String {
            Log.i("ABCD", "hello")
            return "Hello $name"
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT)
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    private fun startForegroundService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notification = Notification.Builder(this, CHANNEL_ID)
                .setContentTitle("前台服务运行中")
                .setContentText("正在执行后台任务...")
                .setSmallIcon(android.R.drawable.ic_notification_clear_all) // 必须设置有效图标
                .build()
            startForeground(NOTIFICATION_ID, notification)
        }
    }
}